package com.chenyue.cm.live.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenyue.cm.base.aop.Log;
import com.chenyue.cm.base.bean.PageVo;
import com.chenyue.cm.base.bean.Pageable;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.utils.RequestUtil;
import com.chenyue.cm.live.domain.JdLiveGoldAward;
import com.chenyue.cm.live.domain.JdLiveRecord;
import com.chenyue.cm.live.domain.JdLiveRecordExample;
import com.chenyue.cm.live.service.JdLiveGoldAwardService;
import com.chenyue.cm.live.service.JdLiveRecordService;
import com.chenyue.cm.live.vo.LiveRecordGoldAward;
import com.chenyue.cm.match.domain.JdMatch;
import com.chenyue.cm.match.domain.JdMatchFormat;
import com.chenyue.cm.match.service.JdMatchFormatService;
import com.chenyue.cm.utils.PageInfoUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenyue-cm
 * @date 2021-07-20
 */
@RestController
@RequestMapping("/jdLiveRecord")
public class JdLiveRecordController {

    private final JdLiveRecordService jdLiveRecordService;

    private final JdMatchFormatService jdMatchFormatService;

    private final JdLiveGoldAwardService liveGoldAwardService;

    public JdLiveRecordController(JdLiveRecordService jdLiveRecordService, JdMatchFormatService jdMatchFormatService, JdLiveGoldAwardService liveGoldAwardService) {
        this.jdLiveRecordService = jdLiveRecordService;
        this.jdMatchFormatService = jdMatchFormatService;
        this.liveGoldAwardService = liveGoldAwardService;
    }

    @RequestMapping("/getList")
    public Success getList(HttpServletRequest request) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        PageVo<JdLiveRecord> result = jdLiveRecordService.getPageBean(pageInfo, JdLiveRecord.class);
        return Success.success(result);
    }

    @RequestMapping("/getLiveRecordList")
    public Success getLiveRecordList(HttpServletRequest request) {
        String id = request.getParameter("id");
        //设置分页信息
        LambdaQueryWrapper<JdLiveRecord> wrapper = new LambdaQueryWrapper<>();
        List<JdLiveRecord> list = jdLiveRecordService.list(wrapper);
        return Success.success(list);
    }

    @RequestMapping("/getRecordGoldAwardList")
    public Success getRecordGoldAwardList(HttpServletRequest request) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        List<LiveRecordGoldAward> returnList = new ArrayList<>();
        //设置分页信息
        PageHelper.startPage(pageInfo.getPageIndex(), pageInfo.getPageSize(), true);
        Map<String, Object> pageSearch = pageInfo.getPageSearch();
        if (pageSearch == null) {
            pageSearch = new HashMap<String, Object>();
        }
        LambdaQueryWrapper<JdLiveRecord> wrapper = new LambdaQueryWrapper<>();
        if (null != pageSearch.get("SEARCH_LIKE_title")) {
            wrapper.like(JdLiveRecord::getTitle, String.valueOf(pageSearch.get("SEARCH_LIKE_title")));
        }
//        pageInfo.setPageSearch(pageSearch);
        wrapper.orderByDesc(JdLiveRecord::getStartTime);
        List<JdLiveRecord> list = jdLiveRecordService.list(wrapper);
        for (JdLiveRecord record : list) {
            LambdaQueryWrapper<JdLiveGoldAward> goldWrapper = new LambdaQueryWrapper<>();
            goldWrapper.eq(JdLiveGoldAward::getLiveRecordId, record.getId())
                    .last("LIMIT 1");
            JdLiveGoldAward award = liveGoldAwardService.getOne(goldWrapper);
            LiveRecordGoldAward recordAward = new LiveRecordGoldAward();
            recordAward.setLiveRecordId(record.getId());
            recordAward.setTitle(record.getTitle());
            recordAward.setLiveLogo(record.getLiveLogo());
            if (null != award) {
                recordAward.setId(award.getId());
                recordAward.setGoldAmount(award.getGoldAmount());
                recordAward.setGetTime(award.getGetTime());
                recordAward.setOnceAmount(award.getOnceAmount());
            }
            returnList.add(recordAward);
        }

        //封装返回结果
        PageInfo<JdLiveRecord> resultSource = new PageInfo<>(list);
        PageInfo<LiveRecordGoldAward> resultTarget = new PageInfo<>(returnList);
        PageInfoUtils<JdLiveRecord,LiveRecordGoldAward> tgObj = new PageInfoUtils<>();
        tgObj.convertPageInfo(resultSource,resultTarget);
        return Success.success(resultTarget);
    }

    /**
     * @param vo 插入实体
     * @return Success
     */
    @Log
    @RequestMapping("/save")
    public Success save(JdLiveRecord vo) {
        boolean success = jdLiveRecordService.save(vo);
        return success ? Success.success() : Success.error();
    }

    /**
     * @param vo      修改实体
     * @param request id
     * @return Success
     */
    @Log
    @RequestMapping("/edit")
    public Success edit(JdLiveRecord vo, HttpServletRequest request) {
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            int success = jdLiveRecordService.getBaseMapper().updateById(vo);
            return success > 0 ? Success.success() : Success.error();
        } else {
            return Success.error("id不能为空");
        }
    }

    /**
     * @param id 主键
     * @return Success
     */
    @Log
    @RequestMapping("/delete/{id}")
    public Success deleteByPrimaryKey(@PathVariable("id") Integer id) {
        JdLiveRecordExample aExample = new JdLiveRecordExample();
        aExample.createCriteria().andIdEqualTo(id);
        int success = jdLiveRecordService.deleteByExample(aExample);
        return success > 0 ? Success.success() : Success.error();
    }

    /**
     * 【API】----  删除多个数据
     *
     * @return Success
     */
    @Log
    @RequestMapping("/delete")
    public Success delete(String ids) {
        String[] idStrings = ids.split(",");
        for (String idString : idStrings) {
            int success = jdLiveRecordService.deleteByPrimaryKey(idString);
            if (success == 0) {
                return Success.error();
            }
        }
        return Success.success();
    }

    @RequestMapping("/getFormatLiveListPage")
    public Success getFormatLiveList(HttpServletRequest request) {
        String formatId = request.getParameter("formatId");
        Pageable pageInfo = RequestUtil.getPageable(request);
        //设置分页信息
        PageHelper.startPage(pageInfo.getPageIndex(), pageInfo.getPageSize(), true);
        LambdaQueryWrapper<JdLiveRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdLiveRecord::getArrangeId, formatId);
        List<JdLiveRecord> list = jdLiveRecordService.list(wrapper);
        //封装返回结果
        PageInfo<JdLiveRecord> result = new PageInfo<>(list);
        return Success.success(result);
    }

    /**
     * @return Success
     */
    @Log
    @RequestMapping("/saveFormatLive")
    public Success saveFormatLive(HttpServletRequest request) {
        String matchId = request.getParameter("matchId");
        String formatId = request.getParameter("formatId");
        String liveList = request.getParameter("liveList");
        //当前赛程
        JdMatchFormat format = jdMatchFormatService.getById(formatId);
        JSONArray formatLiveListArray = null;
        if (null != liveList) {
            JSONObject formatListObject = JSON.parseObject(liveList);
            formatLiveListArray = (JSONArray) formatListObject.get("liveList");
        }
        if (null != formatLiveListArray && formatLiveListArray.size() > 0) {
            for (Object formatLiveListObject : formatLiveListArray) {
                JSONObject formatLiveJsObject = (JSONObject) JSONObject.toJSON(formatLiveListObject);
                Integer recordId = formatLiveJsObject.getInteger("id");
                String title = formatLiveJsObject.getString("title");
                Integer liveId = formatLiveJsObject.getInteger("liveId");
                String liveLogo = formatLiveJsObject.getString("liveLogo");
                if (0 != recordId) {
                    JdLiveRecord record = jdLiveRecordService.getById(recordId);
                    record.setMatchId(Integer.valueOf(matchId));
                    record.setLiveId(liveId);
                    record.setArrangeId(Integer.valueOf(formatId));
                    record.setTitle(title);
                    record.setLiveLogo(liveLogo);
                    record.setStartTime(format.getStartTime());
                    record.setEndTime(format.getEndTime());
                    jdLiveRecordService.updateByPrimaryKey(record);
                } else {
                    JdLiveRecord newRecord = new JdLiveRecord();
                    newRecord.setMatchId(Integer.valueOf(matchId));
                    newRecord.setLiveId(liveId);
                    newRecord.setArrangeId(Integer.valueOf(formatId));
                    newRecord.setTitle(title);
                    newRecord.setLiveLogo(liveLogo);
                    newRecord.setStartTime(format.getStartTime());
                    newRecord.setEndTime(format.getEndTime());
                    jdLiveRecordService.save(newRecord);
                }
            }
        }
        return Success.success();
    }

    @RequestMapping("/getLiveListByFormatId")
    public Success getFormatLiveListByFormatId(HttpServletRequest request) {
        String formatId = request.getParameter("formatId");
        Pageable pageInfo = RequestUtil.getPageable(request);
        //设置分页信息
        PageHelper.startPage(pageInfo.getPageIndex(), pageInfo.getPageSize(), true);
        QueryWrapper<JdLiveRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("arrange_id", formatId);
        List<JdLiveRecord> formatList = jdLiveRecordService.list(wrapper);
        //封装返回结果
        PageInfo<JdLiveRecord> result = new PageInfo<>(formatList);
        return Success.success(result);
    }

}
